package com.ssmfuse.Utils;

import java.lang.reflect.Field;
import java.util.Map;

public class WebUtil {

    public static <T> T parameterToBeans(Map<String, String[]> map, Class<T> clazz) {
        T t = null;

        try {
            t = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        for(Map.Entry<String, String[]> entry : map.entrySet()){


            Field field = null;
            try {
                field = clazz.getDeclaredField(entry.getKey());
            } catch (NoSuchFieldException e) {
            }

            if(field != null){
                field.setAccessible(true);
                try {
                    if(entry.getKey().equals("score")){
                        field.set(t, parseInt(entry.getValue()[0], 0));
                    }else{
                        field.set(t, entry.getValue()[0]);
                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }


        return t;

    }

    //简单比较两个字符串的相似程度
    public static double compareSimilarity(String tar, String origin){
        int res = 0;
        int len = origin.length() > tar.length() ? tar.length() : origin.length();
        for(int i = 0; i < len; i++){
            //如果目标串中前后五个字符有一个  与  原始串匹配  就算 匹配成功
            int st = (i - 5) >= 0 ? (i - 5) : 0;
            int len2 = (st + 10) <= tar.length() ? (st + 10) : tar.length();
            String substring = tar.substring(st, len2);
            if(substring.contains("" + origin.charAt(i))){
                res += 1;
            }
        }

        return res * 1.0 / tar.length();
    }




    public static int parseInt(String str, int val){
        try {
            int i = Integer.parseInt(str);
            return i;
        }catch (Exception e){
            return val;
        }
    }


}



